<?php
class mobileAction extends HomeAction {

    protected function _initialize() {
        $freeAuth = array('login', 'liveTest',"share","quche"); //在微信端不用置入openid的方法

        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == false && ACTION_NAME!="liveTest") {
            /* redirect(U('toWX'));
            exit;//非微信端 */
            $this->assign("Server",'other');//非微信端
            $_SESSION['Server'] = 'other';
        }else if(!in_array(ACTION_NAME, $freeAuth)){
            $this->assign("Server",'wx');//非微信端
            $_SESSION['Server'] = 'wx';
            if($_REQUEST['open_id']){
                $_SESSION['open_id'] = $_REQUEST['open_id'];
            }
            if(empty($_SESSION['open_id'])) {
                vendor('WxPay/WxPayPubHelper');
                $jsApi = new JsApi_pub();
                if (!isset($_GET['code'])){

                    $url=C('WEB_URL').'mobile/'.ACTION_NAME.'/';
                    $url = $jsApi->createOauthUrlForCode($url);
                    Header("Location: $url");exit("数据初始化中..");
                }else{
                    $code = $_GET['code'];
                    $jsApi->setCode($code);
                    $_SESSION['open_id'] = $jsApi->getOpenId();
                }
                unset($_SESSION['user']);
            }
            if(empty($_SESSION['user']) && !empty($_SESSION['open_id'])){
                $Info = M('user')->field('user_id,open_id,username,nickname,realname,address')->where("open_id='".$_SESSION['open_id']."'")->find();
                if($Info){                                  //初始化验证用户
                    $U = M('user_auto');
                    $model = $U->join('hx_auto_model m on hx_user_auto.model_id=m.model_id')->where("user_id=".$Info['user_id']." and hx_user_auto.default=1")->find();

                    $Info['model'] = $model;
                    $_SESSION['order']['model_id'] = $model['model_id'];
                    $_SESSION['order']['realname']=$Info["realname"];
                    $_SESSION['order']['phone']=$Info["username"];
                    $_SESSION['user'] = $Info;              //session记录数据
                    $_SESSION['location']=$Info['city'];
                }
            }
        }
    }

    public function warnSms(){
        log::write("定时执行测试");
        $Model = M('order');

        $start=strtotime(date('Y-m-d',strtotime('+1 day')));
        $end=strtotime(date('Y-m-d',strtotime('+2 day')));

        $map['yy_date'] = array('in',"$start,$end");
        $timeArr=array(1=>"9:00至11:00",2=>"11:00至13:00",3=>"13:00至15:00",4=>"15:00至17:00",5=>"17:00至19:00",6=>"19:00至21:00");

        $list = $Model->field("username,order_name,realname,order_id,yy_date,yy_time,hx_order.create_time")->join("hx_user ON hx_user.user_id=hx_order.user_id")->where($map)->select();
        foreach($list as $key => $value){
            $content="尊敬的用户，您好！您于".date("m月d号H",$value['create_time'])."时预约了".$value['order_name']."服务，预约时间为：".date("m月d号",$value['yy_date']).$timeArr[$value['yy_time']]."，请准时到达。如有问题，请咨询客服热线：400-673-0088。谢谢您的支持！";
            $this->postSms($value['username'],$content);
        }
    }

    public function city(){
        if(!empty($_GET['id'])){
            $_SESSION['location']=$_GET['id'];
            if(!empty($_SESSION['user']['user_id'])){
                $res=M("user")->where("user_id=".$_SESSION['user']['user_id'])->setField("city",$_GET['id']);
            }
            redirect(U('index'));
        }else{
            $this->display();
        }
    }
    
    public function index(){

        if(empty($_SESSION['location'])&&ACTION_NAME!="live"){
            redirect(U('city'));
        }

        if(!empty($_GET["autoId"])){
            $_SESSION['order']['model_id']=$_GET['autoId'];
        }
        if(!empty($_SESSION['order']['model_id'])){
            $mapAuto['model_id']=$_SESSION['order']['model_id'];
            $auto=M("auto_model")->where($mapAuto)->find();
            $this->assign("auto",$auto);
        }


        $PJ=M("peijian");
        $jiyou=$PJ->where("type_id=1 and status=3")->order("pj_csprice desc")->select();
        
        $jiyouList=array();

        //判断使用机油等级
        $jiyouArr=C("JIYOU");

        $jiyouL1Id=empty($_SESSION['order']['jyId'])?260:$_SESSION['order']['jyId'];//默认普通4升机油
        $_SESSION['order']['jyDef']=$jiyouL1Id;
        $jiyouL2Id=260;//大众型套餐机油
        $jiyouL3Id=263;//经济套餐机油
        $jiyouL4Id=254;//豪华套餐机油

        if(!empty($_GET["autoId"])&&in_array($auto['brand_id'],array(1,2,8,9,11,14,15,36,62,65,67,70,73,85,88,119,152))){
            $jiyouL1Id=254;//默认普通4升机油
        }

        for($i=0;$i<count($jiyou);$i++){
            //不同套餐4升机油
            if($jiyou[$i]['pj_id']==$jiyouL1Id){
                $jiyouList[0]=$jiyou[$i];
            }
            if($jiyou[$i]['pj_id']==$jiyouL2Id){
                $jiyouList[1]=$jiyou[$i];
            }
            if($jiyou[$i]['pj_id']==$jiyouL3Id){
                $jiyouList[2]=$jiyou[$i];
            }
            if($jiyou[$i]['pj_id']==$jiyouL4Id){
                $jiyouList[3]=$jiyou[$i];
            }

            //不同套餐1升机油
            if($jiyou[$i]['pj_id']==$jiyouArr[$jiyouL1Id]){
                $jiyouOne[0]=$jiyou[$i];
            }
            if($jiyou[$i]['pj_id']==$jiyouArr[$jiyouL2Id]){
                $jiyouOne[1]=$jiyou[$i];
            }
            if($jiyou[$i]['pj_id']==$jiyouArr[$jiyouL3Id]){
                $jiyouOne[2]=$jiyou[$i];
            }
            if($jiyou[$i]['pj_id']==$jiyouArr[$jiyouL4Id]){
                $jiyouOne[3]=$jiyou[$i];
            }

            if($jiyou[$i]['weight']==4){
                if($jiyou[$i]["pj_id"]==286){
                    array_unshift($jiyouFour,$jiyou[$i]);
                }else{
                    $jiyouFour[]=$jiyou[$i];
                }
            }
            if(in_array($jiyou[$i]['pj_id'], array(2))){
                $peijianOther[]=$jiyou[$i];
            }

        }
        ksort($jiyouList);
        ksort($jiyouOne);



        $this->assign("peijianOther",$peijianOther);
        $this->assign("jiyouFour",$jiyouFour);
        $this->assign("jiyouOne",$jiyouOne);
        $this->assign("jiyou",$jiyouList);


        //获取机滤
        if(!empty($_SESSION['order']['model_id'])){
            $J=M("jl");
            $jilv=$J->where($mapAuto)->select();
            for($i=0;$i<count($jilv);$i++){
                $jilvId[]=$jilv[$i]['pj_id'];
            }

            
            $mapJV['pj_id']=array("in",implode(",",$jilvId));
            $jilv=$PJ->where($mapJV)->select();

            for($i=0;$i<count($jilv);$i++){
                if($jilv[$i]['count']>0){
                    $jilvData=$jilv[$i];
                    break;
                }
            }
        }
        
        if(empty($jilvData)){
            $jilvData=$PJ->where("pj_id=278")->find();
        }
        $this->assign("jilv",$jilvData);
        //是否已有免单券
        if(!empty($_SESSION['user']['user_id'])){
            $couponT=M('coupon_user');
            $already = $couponT->field("status,rand_money")->where('c_id=4 and user_id='.$_SESSION['user']['user_id'])->find();
            $this->assign("already",$already);
        }

        $_SESSION['order']['jvDefId']=$jilv['pj_id'];
 
        $this->display();
        
    }


    public function step1(){
        //首页跳至
        if(!empty($_GET['jyId'])){
            $_SESSION['order']['jyId']=$_GET['jyId'];
            $_SESSION['order']['jvId']=$_GET['jvId'];
            $_SESSION['order']['otherPJ']=$_GET['otherPJ'];
            $_SESSION['order']['totalPrice']=$_GET['price'];
            $_SESSION['order']['priceJY']=$_GET['priceJY'];
            
        }
        $_SESSION['order']['wx_id']=$_GET['wx_id'];

        if($_SESSION['location']!="3301"){
            $_SESSION['order']['wx_id']="";
        }

        if(!empty($_SESSION['order']['model_id'])&&empty($_GET['choose'])){
            redirect(U('step2').'?total='.$_GET['price']."&t=".time());
        }
        
        $ao = M('auto');
        $field = "hx_auto.brand_id,brand_name,brand_logo,letter";//,pinyin,model_id,model_name,model_pl,model_year";
        $join  = "hx_auto_model ON hx_auto.brand_id=hx_auto_model.brand_id";
        $autoList  = $ao->field($field)->order("letter asc ,brand_id asc")->select();
        
        foreach ($autoList as $key=>$value){
            foreach($value as $ke=>$val){
                if($val==$value['letter']){
                    $list[$val['letter']][] = $value;
                }
            }
        }
        
        if(!empty($_REQUEST['h'])){
            $this->ajaxReturn($list,"选择品牌",1);
        }
        $this->assign('list',$list);
        $this->display();
    }

    public function step2(){

        if(!empty($_GET["autoId"])){
            $_SESSION['order']['model_id']=$_GET["autoId"];
        }else if(empty($_SESSION['order']['model_id'])){
            redirect(U('step1'));
        }

        $field="pj_id,pj_name,pj_csprice,pj_scprice,logo,pj_xinghao,pj_pinpai,weight";
        $tempPrice=$_SESSION['order']['totalPrice']-$_SESSION['order']['priceJY'];  //除机油外其他产品价格
        $capacity=M("auto_model")->where("model_id=".$_SESSION['order']['model_id'])->getField("capacity");
        $pj=M("peijian");

        $jyF=$pj->field($field)->where("pj_id=".$_SESSION['order']['jyId'])->find();
        $jyF['count']=floor($capacity/4);
        $price= $jyF['count']*$jyF['pj_csprice'];

        if($_SESSION['order']['jyId']==287||$_SESSION['order']['jyId']==293){
            //金美孚和速霸2000特殊处理
            $jyF['count']=$capacity;
        }else if($capacity%4!=0){

            $mapOne['pj_id']=C("JIYOU")[$_SESSION['order']['jyId']];

            $jyO=$pj->field($field)->where($mapOne)->find();

            $jyO['count']=$capacity%4;
            $price+=$jyO['count']%4*$jyO['pj_csprice'];
            $this->assign("jyO",$jyO);
        }

        $this->assign("jyF",$jyF);
        

        $jv=$pj->field($field)->where("pj_id=".$_SESSION['order']['jvId'])->find();
        $this->assign("jv",$jv);

        
        

        $_SESSION['order']['priceJY']=$price;


        $mapAuto['model_id']=$_SESSION['order']['model_id'];
        $auto=M("auto_model")->where($mapAuto)->find();
        $this->assign("auto",$auto);

        //优惠券
        if(!empty($_SESSION['user'])){
            $couponT=M('coupon_user');

            if($_SESSION['order']['totalPrice']>=299){
                $mapCoupon['user_id'] = $_SESSION['user']['user_id'];
                $mapCoupon['status'] = array("gt",0);
                $mapCoupon['c_id']=array("neq",5);
                $couponList =$couponT->join("left join hx_coupon as c ON c.c_id=hx_coupon_user.c_id")->where($mapCoupon)->select();
                $this->assign("couponList",$couponList);
            }

            //是否已有免单券
            $already = $couponT->field("status,rand_money")->where('c_id=4 and user_id='.$_SESSION['user']['user_id'])->find();

            if($already['status']==1){
                $youhuiOther=$_SESSION['order']['totalPrice']-$_SESSION['order']['priceJY'];

                $youhui=$youhuiOther+($_SESSION['order']['priceJY']>200?200:$_SESSION['order']['priceJY']);
                $youhui=$youhui>$already['rand_money']?$already['rand_money']:$youhui;
                $this->assign("youhui",$youhui);
            }

            $this->assign("already",$already['status']);
            
        }

        $_GET['total']=empty($_GET['total'])?$price+$jv['pj_csprice']:$_GET['total'];

        if($_SESSION['order']['wx_id']==441){
            $C=M("company");
            $_SESSION['order']['totalPrice']= $_GET['total']+150;
            $map['wx_id']=$_SESSION['order']['wx_id'];
            $company=$C->where($map)->find();
            $this->assign("company",$company);

            $this->display("HZstep2");
            exit;
        }



        $address=$_SESSION['user']['address']==""?$_SESSION['order']['address']:$_SESSION['order']['address'];


        $this->assign("address",$_SESSION['order']['address']);
        $this->display();
    }

    //移动端创建订单前置方法
    public function createOrder(){
        $_SESSION['order']['source']=$_POST['source'];
        $_SESSION['order']['goodsId']=$_SESSION['order']['jyId'].",".$_SESSION['order']['jvId'];
        $_SESSION['order']['otherPJ']=empty($_POST['otherPJ'])?null:$_POST['otherPJ'];

        $_SESSION['order']['realname']=$_POST["realname"];
        $_SESSION['order']['phone']=$_POST["phone"];
        $_SESSION['order']['address']=$_POST["address"];

        $_SESSION['user']['realname']=$_POST["realname"];
        $_SESSION['user']['address']=$_POST["address"];

        $this->saveOrder();
    }


    public function step3(){
        if($_SESSION['order']['wx_id']==441){
            redirect(U('step4')."?wx_id=".$_SESSION['order']['wx_id']."&wx_name=去保养杭州萧杭路店");
        }
        
        $map['wx_id']=array("in","8,20,23,39,135,145,221,271,275,277,378,424,432,433,434,435,436,437,438,439");
        $C=M("company");

        $company = $C->where($map)->order('zone desc')->select();
        $this->assign('company', $company);

        $ourCompany = $C->where("wx_id=441")->select();
        $this->assign('ourCompany', $ourCompany);
        
        $this->display();
    }

    public function step4(){

        if(!empty($_GET['wx_id'])){
            $_SESSION['order']['wx_id']=$_GET["wx_id"];
            $_SESSION['order']['wx_name']=$_GET["wx_name"];
            $_SESSION['order']['wx_address']=$_GET["wx_address"];

            $data['wx_id']=$_SESSION['order']['wx_id'];
            $data['company']=$_SESSION['order']['wx_name'];
            $data['order_id']=$_SESSION['order']['order_id'];
            $res=M("order")->save($data);
        }

        
        
        if($_GET['type']=="yuyue"){
            $txt="恭喜您！预约成功";
            $content="尊敬的".$_SESSION['order']['realname']."用户,您好!您的预约已受理，我们的客服人员会尽快与您取得联系并确认预约信息。如有疑问，请拨打客服热线:400-673-0088";

            //给客服发信息
            $this->postSms(C("kefuPhone"),"收到新的预约信息，手机号：".$_SESSION['user']['username']."姓名：".$_SESSION['order']['realname']);

        }else{
            $txt="下单成功，我们会尽快安排发货！";
            $content="尊敬的".$_SESSION['order']['realname']."用户,您好!您的订单已受理，我们的工作人员会尽快安排发货，谢谢您的支持!如有疑问，请拨打客服热线:400-673-0088";

        }
        $this->postSms($_SESSION['user']['username'],$content);

        $this->assign("txt",$txt);
        $this->display();
    }

    //获取服务相关配件
    public function getServiceGoods(){

        $serviceType=array(3=>10003,4=>10002,5=>10001);   //服务对应配件ID，只针对于全车系通用的服务
        $map['pj_id']=$serviceType[$_POST['type']];
        $P=M("peijian");
        $peijian=$P->where($map)->select();
        if($peijian){
            $this->ajaxReturn($peijian,C("serverCode")[$_POST['type']],1);
        }else{
            $this->ajaxReturn(false,"获取失败",0);
        }
        
    }

    //刮刮卡活动
    public function actgg(){
        $AllCount = M('coupon')->field('sum,get_count')->where('c_id=4')->find();           //总参与次数
        $time = time();                                                             //服务器时间戳
        $date = date("Y-m-d");                                                      //当前服务器日期
        $am = strtotime($date." 00:00:00");                                         //上午时间戳
        $pm = strtotime($date." 23:59:59");                                         //下午时间戳
        $Last = 0;  
        $couponT=M('coupon_user');                                              //剩余名额

        if($time>=$am && $time<=$pm){                                               //11~16
            $Last = $couponT->field('count(id) as count')->where("get_time>='$am' and get_time<='$pm' and c_id=4")->find();         
        }elseif($time>=$pm){                                                        //16~24
            $Last = $couponT->field('count(id) as count')->where("get_time>='$pm' and c_id=4")->find();
        }
        
        
        if($_SESSION['user']['user_id']){
            $CUser = $couponT->where('c_id=4 and user_id='.$_SESSION['user']['user_id'])->getField("status");
            $this->assign("already",$CUser);        //是否已有免单券

        }
        
        $this->assign("AllCount",$AllCount);            //抢票人次
        $this->assign("Last",50-$Last['count']);  
        $this->assign("date",$date);
        $this->assign("time",$time);
        $this->display();
    }


    public function myOrder(){
        if(empty($_SESSION['user'])){
            redirect(U('login')."?back=Order");
        }

        $map['user_id']=$_SESSION['user']['user_id'];
        $map['order_name']=array('neq','');

        //$map['type']=array('in',"1,2,999");   //只取包含大小保养的订单

        if($map['user_id']==753){
            unset($map['user_id']);
        }

        $field="order_id,order_num,order_name,user_id,total_price,all_price,create_time,status,wx_id,service_price,is_comment,pay_type,km";
        $PO=M("order");
        $order=$PO->field($field)->where($map)->order("order_id desc")->select();
        $this->assign("statusArr",C("orderStatus"));
        $this->assign("statusArrOffice",C("orderStatusOffice"));
        $this->assign("order",$order);
        $this->display();
    }
    
    public function myOrderReport(){
        if(empty($_SESSION['user'])){
            redirect(U('login')."?back=Order");
        }
        $order = M('order');
        $orderlog = M('order_log');

        $map['order_id'] = $_REQUEST['id'];
        $order = $order->where($map)->find();
        $list = $orderlog->where($map)->order("log_id desc")->select();

        $data =  array();
        $Unit = C('UNIT');
        $car = array();
        $yy = array();
        foreach ($list as $li){
            if($li['image']){
                $image = json_decode($li['image']);
                $img = array();
                foreach ($image as $i){
                    $img[] = @C(WEB_URL).$i;
                }
                $li['image'] = $img;
            }
            
            switch ($li['name']){
                case "火花塞点火间隙":
                            $huo = json_decode($li['val']);
                            if($huo->type==1){
                                $li['name'] = '白金式火花塞';
                                $li['biaozhun'] = '白金式火花塞间隙通常为0.6mm,最大0.8mm;';
                            }elseif($huo->type==2){
                                $li['name'] = '电子式火花塞';
                                $li['biaozhun'] = '电子式火花塞间隙通常为0.7mm,最大1.2mm;';
                            }
                            if($huo->value>0.6 && $huo->value<0.8 && $huo->type==1){
                                $li['val'] = $huo->value;
                                $li['compare'] = '正常';
                            }elseif($huo->value>0.7 && $huo->value<1.2 && $huo->type==2){
                                $li['val'] = $huo->value;
                                $li['compare'] = '正常';
                            }else{
                                $li['val'] = $huo->value;
                                $li['compare'] = '需更换';
                            }
                          break;
                        case "冷却液冰点":
                          $li['biaozhun'] = '标准值小于-15°C';
                          if($li['val']<-15){
                            $li['compare'] = '正常';
                          }else{
                            $li['compare'] = '需更换';
                          }
                          break;
                        case "转向油使用里程":
                          $li['biaozhun'] = '两年或两万公里更换';
                          if($li['val']<=20000){
                            $li['compare'] = '正常';
                          }else{
                            $li['compare'] = '需更换';
                          }
                          break;
                        case "变速箱油使用里程":
                            $li['biaozhun'] = '六万公里更换';
                            if($li['val']<=60000){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '需更换';
                            }
                            break;
                        case "前刹车盘单面磨损厚度":
                            $li['biaozhun'] = '磨损超过1.5MM需更换';
                            if($li['val']<1.5){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '需更换';
                            }
                            break;
                        case "后刹车盘单面磨损厚度":
                            $li['biaozhun'] = '磨损超过1.5MM需更换';
                            if($li['val']<1.5){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '需更换';
                            }
                            break;
                        case "前刹车片厚度":
                            $li['biaozhun'] = '厚度低于3MM需更换';
                            if($li['val']>3){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '需更换';
                            }
                            break;
                        case "后刹车片厚度":
                            $li['biaozhun'] = '厚度低于3MM需更换';
                            if($li['val']>3){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '需更换';
                            }
                            break;
                        case "刹车油含水量":
                            $li['biaozhun'] = '含水量超过3%必须更换';
                            if($li['val']<=3){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '需更换';
                            }
                            break;
                        case "左前轮胎纹厚度":
                            $li['biaozhun'] = '花纹深度在1.6mm需更换';
                            if($li['val']>=1.6){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '需更换';
                            }
                            break;
                        case "右前轮胎纹厚度":
                            $li['biaozhun'] = '花纹深度在1.6mm需更换';
                            if($li['val']>=1.6){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '需更换';
                            }
                            break;
                        case "左后轮胎纹厚度":
                            $li['biaozhun'] = '花纹深度在1.6mm需更换';
                            if($li['val']>=1.6){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '需更换';
                            };
                            break;
                        case "右后轮胎纹厚度":
                            $li['biaozhun'] = '花纹深度在1.6mm需更换';
                            if($li['val']>=1.6){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '需更换';
                            }
                            break;
                        case "空调滤芯PM2.5检测":
                            $li['biaozhun'] = '0~75 ug/m³良好,大于正常值需更换';
                            if($li['val']<=35){
                                $li['compare'] = '正常';
                            }elseif($li['val']>35 && $li['val']<=75){
                                $li['compare'] = '正常';
                            }elseif($li['val']>75 && $li['val']<=115){
                                $li['compare'] = '轻度污染';
                            }elseif($li['val']>115 && $li['val']<=150){
                                $li['compare'] = '中度污染需更换';
                            }elseif($li['val']>150 && $li['val']<=250){
                                $li['compare'] = '重度污染需更换';
                            }else{
                                $li['compare'] = '严重污染需更换';
                            }
                            break;
                        case "制冷效果检测":
                            $li['biaozhun']='测量值小于12°C为正常';
                            if($li['val']<=12){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '异常';
                            }
                            break;
                        default:;
            }
            
            if($li['type'] == 'yj' && $li['action_id'] == '4.2.2'){
                $li['val'] = $li['val'].' km';
            }elseif($li['type'] == 'sg'){
                if($Unit[$li['action_id']]){
                    $li['val'] = $li['val'].' '.$Unit[$li['action_id']];
                }
            }
            
            if($li['action_id']=='2.2'){
                $car = $li;
            }elseif($li['action_id']=='8'){
                $yy = $li;
            }else{
                $data[] = $li;
            }
        }
        if($car['val_type']==5){
            $car['val'] = json_decode($car['val'],true);
        }
        $this->assign("order",$order);
        $this->assign("orderlog",$data);    
        $this->assign("car",$car);
        $this->assign("yy",$yy);
        $this->display();
    }
    
    public function myCoupon(){
        if(empty($_SESSION['user'])){
            redirect(U('login')."?back=Coupon");
        }

        $user_id = $_SESSION['user']['user_id'];
        $couponT=M('coupon_user as l');
        $couponList = $couponT->join("left join hx_coupon as c ON c.c_id=l.c_id")->field('c.c_id,l.number,l.code,l.rand_money,l.status,c.money,c.content,c.low_money,c.high_money,c.type,c.end_time')->where("user_id=$user_id")->select();
        $this->assign("couponList",$couponList);
        $this->display();
    }

    public function myOrderInfo(){
        if(empty($_SESSION['user'])){
            redirect(U('login')."?back=Order");
        }
        $map['hx_order.user_id']=$_SESSION['user']['user_id'];
        $map['hx_order.order_id']=$_GET['id'];
        $field="order_id,order_num,order_name,user_id,total_price,pay_type,hx_order.create_time,hx_order.status,wx_name,headImage,hx_company.wx_address,brand_name,model_name,model_pl,model_year,brand_logo,all_price,order_name";
        $PO=M("order");
        $order=$PO->field($field)->where($map)->join("hx_company ON hx_company.wx_id=hx_order.wx_id")->join("hx_auto_model ON hx_auto_model.model_id=hx_order.model_id")->find();
        $orderStatus=C("orderStatus");
        $mapPart['order_id']=$_GET['id'];
        $partList=M("order_info")->where($mapPart)->select();

        $comment=M("comment")->where($mapPart)->find();
        if($order['pay_type'] == 0  && $_SESSION['Server'] == 'wx'){
            $this->assign("jsApiParameters",$this->pay($mapPart['order_id']));
        }

        $this->assign("comment",$comment);
        $this->assign("partList",$partList);
        $this->assign("orderStatus",$orderStatus);
        $this->assign("order",$order);
        $this->assign("log",$this->stepList($_GET['id']));
        $this->display();
    }


    /*验证*/
    public function getCode() {
        $U = M("user");
        $data['username'] = $_POST['username'];
        $res = $U->where($data)->getField("user_id");
        if (!$res) {
            $this->ajaxReturn(null, "该手机未注册，请注册后登录", -3);
        }


        $S = M("sms");
        if (empty($_POST['pwd'])) {   //获取验证码
            $randStr = str_shuffle('1234567890');
            $rand = substr($randStr, 0, 6);
            import("@.ORG.MobileSms");
            $mobilesms = new MobileSms();

            $sms['to_phone'] = $_POST['username'];
            $sms['content'] = "您的验证码是：" . $rand . "。请在5分钟内使用，过期无效！";

            $rs = $mobilesms->send($sms['to_phone'], $sms['content']);
            if ($rs !== false) {
                $sms['type'] = 2;
                $sms['create_time'] = time();
                $sms['isused'] = 0;
                $sms['desc'] = $rand;
                $sms["out_id"] = $rs;

                $res = $S->add($sms);
                if ($res) {
                    $this->ajaxReturn(true, "验证码发送成功", 1);
                } else {
                    $this->ajaxReturn(null, "发送验证码失败，请重试", -7);
                }
            }
        }
    }

    //直营店安装订单详情
    public function myOrderInfoQBY(){
        if(empty($_SESSION['user'])){
            redirect(U('login')."?back=Order");
        }
        $map['order_id'] = $_REQUEST['id'];
        $Model = M('order');
        $order = $Model->join('hx_user_auto ua on hx_order.ua_id=ua.ua_id')->join('hx_auto_model m on hx_order.model_id=m.model_id')->field('hx_order.*,ua.vin,ua.number,m.*')->where($map)->find();

        $partList = M('order_info')->where($map)->select();
        $log=M("order_log")->field("action_id,name,val,bad_level,type")->where($map)->order("log_id desc")->select();
        $data =  array();
        $Unit = C('UNIT');
        foreach ($log as $li){
            switch ($li['name']){
                case "火花塞点火间隙":
                    $huo = json_decode($li['val']);
                    if($huo->type==1){
                        $li['name'] = '白金式火花塞';
                        $li['biaozhun'] = '0.6mm至0.8mm';
                    }elseif($huo->type==2){
                        $li['name'] = '电子式火花塞';
                        $li['biaozhun'] = '0.7mm至1.2mm';
                    }
                    if($huo->value>0.6 && $huo->value<0.8 && $huo->type==1){
                        $li['val'] = $huo->value;
                        $li['compare'] = '正常';
                    }elseif($huo->value>0.7 && $huo->value<1.2 && $huo->type==2){
                        $li['val'] = $huo->value;
                        $li['compare'] = '正常';
                    }else{
                        $li['val'] = $huo->value;
                        $li['compare'] = '需更换';
                    }
                  break;
                case "冷却液冰点":

                    $li['biaozhun'] = '标准值小于-15°C';
                    if($li['val']<-15){
                        $li['compare'] = '正常';
                      }else{
                        $li['compare'] = '需更换';
                      }
                      break;
                    case "转向油使用里程":
                      $li['biaozhun'] = '两年或两万公里更换';
                      if($li['val']<=20000){
                        $li['compare'] = '正常';
                      }else{
                        $li['compare'] = '需更换';
                      }
                      break;
                    case "变速箱油使用里程":
                        $li['biaozhun'] = '六万公里更换';
                        if($li['val']<=60000){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "前刹车盘单面磨损厚度":
                        $li['biaozhun'] = '磨损超过1.5MM需更换';
                        if($li['val']<1.5){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "后刹车盘单面磨损厚度":
                        $li['biaozhun'] = '磨损超过1.5MM需更换';
                        if($li['val']<1.5){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "前刹车片厚度":
                        $li['biaozhun'] = '磨损低于3MM需更换';
                        if($li['val']>3){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "后刹车片厚度":
                        $li['biaozhun'] = '磨损低于3MM需更换';
                        if($li['val']>3){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "刹车油含水量":
                        $li['biaozhun'] = '含水量超过3%必须更换';
                        if($li['val']<=3){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "左前轮胎纹厚度":
                        $li['biaozhun'] = '胎纹厚度需大于1.6mm';
                        if($li['val']>=1.6){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "右前轮胎纹厚度":
                        $li['biaozhun'] = '胎纹厚度需大于1.6mm';
                        if($li['val']>=1.6){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "左后轮胎纹厚度":
                        $li['biaozhun'] = '胎纹厚度需大于1.6mm';
                        if($li['val']>=1.6){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        };
                    break;
                    case "右后轮胎纹厚度":
                        $li['biaozhun'] = '胎纹厚度需大于1.6mm';
                        if($li['val']>=1.6){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "空调滤芯PM2.5检测":
                        $li['biaozhun'] = '0~75 ug/m³为良好';
                        if($li['val']<=35){
                            $li['compare'] = '正常';
                        }elseif($li['val']>35 && $li['val']<=75){
                            $li['compare'] = '正常';
                        }elseif($li['val']>75 && $li['val']<=115){
                            $li['compare'] = '轻度污染';
                        }elseif($li['val']>115 && $li['val']<=150){
                            $li['compare'] = '中度污染需更换';
                        }elseif($li['val']>150 && $li['val']<=250){
                            $li['compare'] = '重度污染需更换';
                        }else{
                            $li['compare'] = '严重污染需更换';
                        }
                        break;
                    case "制冷效果检测":
                        $li['biaozhun']='测量值小于12°C为正常';
                        if($li['val']<=12){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '异常';
                        }
                        break;
                    default:;
            }
            if($li['type'] == 'yj' && $li['action_id'] == '4.2.2'){
                $li['val'] = $li['val'].' km';
            }elseif($li['type'] == 'sg'){
                if($Unit[$li['action_id']]){
                    $li['val'] = $li['val'].' '.$Unit[$li['action_id']];
                }
            }
            $data[] = $li;
        }

        $comment=M("comment")->where($map)->find();

        $nonceStr="99qby";
        cache('signature',null);  //清除JSSDK调用权限缓存，只限测试时执行
        if(cache('signature')!=""){
            $this->assign("signature",cache('signature'));
            $this->assign("signatureTime",cache('signatureTime'));
            $this->assign("nonceStr",$nonceStr);
        }else if($order['status']==60&&$order['privilege']==""&&$order['pay_type']==0){
            $t=time();
            $signature=$this->getJsapiTicket($t,$nonceStr);  //签名随机值;
            
            cache(array('type'=>'file','expire'=>3600));
            cache('signature', $signature);
            cache('signatureTime', $t);

            $this->assign("nonceStr",$nonceStr);
            $this->assign("signatureTime",cache('signatureTime'));
            $this->assign("signature",cache('signature'));
        }

        if($order['cu_id']!=0){
            $coupon=M("coupon_user")->where("cu_id=".$order['cu_id'])->find();
            if($coupon){
                $this->assign("coupon",$coupon);
            }
        }

        $this->assign('comment', $comment);
        $this->assign('log', $data);
        $this->assign('lastLog', $log[0]);
        $this->assign('order', $order);
        $this->assign('partList', $partList);
        $this->assign('company', 1);    //默认维修厂 － 去保养

        if($order['type']==10){
            $this->display("summerInfo");
            exit;
        }
        $this->display();
    }

    public function share(){
        $O=M("order");
        $map['order_id']=$_GET['id'];
        $order=$O->field("model_id,total_price,all_price,js_id")->where($map)->find();
        $auto=M("auto_model")->where("model_id=".$order['model_id'])->find();
        $partList = M('order_info')->where($map)->select();
        $log=M("order_log")->field("action_id,name,val,bad_level,type,time,image")->where($map)->order("log_id desc")->select();

        $data =  array();
        $Unit = C('UNIT');
        foreach ($log as $li){
            switch ($li['name']){
                case "火花塞点火间隙":
                    $huo = json_decode($li['val']);
                    if($huo->type==1){
                        $li['name'] = '白金式火花塞';
                        $li['biaozhun'] = '0.6mm至0.8mm';
                    }elseif($huo->type==2){
                        $li['name'] = '电子式火花塞';
                        $li['biaozhun'] = '0.7mm至1.2mm';
                    }
                    if($huo->value>0.6 && $huo->value<0.8 && $huo->type==1){
                        $li['val'] = $huo->value;
                        $li['compare'] = '正常';
                    }elseif($huo->value>0.7 && $huo->value<1.2 && $huo->type==2){
                        $li['val'] = $huo->value;
                        $li['compare'] = '正常';
                    }else{
                        $li['val'] = $huo->value;
                        $li['compare'] = '需更换';
                    }
                  break;
                case "冷却液冰点":

                    $li['biaozhun'] = '标准值小于-15°C';
                    if($li['val']<-15){
                        $li['compare'] = '正常';
                      }else{
                        $li['compare'] = '需更换';
                      }
                      break;
                    case "转向油使用里程":
                      $li['biaozhun'] = '两年或两万公里更换';
                      if($li['val']<=20000){
                        $li['compare'] = '正常';
                      }else{
                        $li['compare'] = '需更换';
                      }
                      break;
                    case "变速箱油使用里程":
                        $li['biaozhun'] = '六万公里更换';
                        if($li['val']<=60000){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "前刹车盘磨损":
                        $li['biaozhun'] = '磨损超过3MM需更换';
                        if($li['val']<3){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "后刹车盘磨损":
                        $li['biaozhun'] = '磨损超过3MM需更换';
                        if($li['val']<3){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "前刹车片厚度":
                        $li['biaozhun'] = '磨损低于3MM需更换';
                        if($li['val']>3){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "后刹车片厚度":
                        $li['biaozhun'] = '磨损低于3MM需更换';
                        if($li['val']>3){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "刹车油含水量":
                        $li['biaozhun'] = '含水量超过3%必须更换';
                        if($li['val']<=3){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "左前轮胎纹厚度":
                        $li['biaozhun'] = '胎纹厚度需大于1.6mm';
                        if($li['val']>=1.6){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "右前轮胎纹厚度":
                        $li['biaozhun'] = '胎纹厚度需大于1.6mm';
                        if($li['val']>=1.6){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "左后轮胎纹厚度":
                        $li['biaozhun'] = '胎纹厚度需大于1.6mm';
                        if($li['val']>=1.6){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        };
                    break;
                    case "右后轮胎纹厚度":
                        $li['biaozhun'] = '胎纹厚度需大于1.6mm';
                        if($li['val']>=1.6){
                            $li['compare'] = '正常';
                        }else{
                            $li['compare'] = '需更换';
                        }
                        break;
                    case "空调滤芯PM2.5检测":
                        $li['biaozhun'] = '0~75 ug/m³为良好';
                        if($li['val']<=35){
                            $li['compare'] = '正常';
                        }elseif($li['val']>35 && $li['val']<=75){
                            $li['compare'] = '正常';
                        }elseif($li['val']>75 && $li['val']<=115){
                            $li['compare'] = '轻度污染';
                        }elseif($li['val']>115 && $li['val']<=150){
                            $li['compare'] = '中度污染需更换';
                        }elseif($li['val']>150 && $li['val']<=250){
                            $li['compare'] = '重度污染需更换';
                        }else{
                            $li['compare'] = '严重污染需更换';
                        }
                        break;
                    case "制冷效果检测":
                            $li['biaozhun']='测量值小于12°C为正常';
                            if($li['val']<=12){
                                $li['compare'] = '正常';
                            }else{
                                $li['compare'] = '异常';
                            }
                            break;
                        default:;
            }
            if($li['type'] == 'yj' && $li['action_id'] == '4.2.2'){
                $li['val'] = $li['val'].' km';
            }elseif($li['type'] == 'sg'){
                if($Unit[$li['action_id']]){
                    $li['val'] = $li['val'].' '.$Unit[$li['action_id']];
                }
            }
            $data[] = $li;
        }

        $signature=M("jishi")->where("js_id=".$order['js_id'])->getField("signature");
        $this->assign('signature', $signature);

        for($i=0;$i<count($data);$i++){
            if($data[$i]['action_id']=="2.3"){
                $pic=json_decode($data[$i]['image'],true);
                break;
            }
        }

        $this->assign('pic',$pic);
        $this->assign('log', $data);
        $this->assign('lastLog', $log[0]);
        $this->assign('order', $order);
        $this->assign('partList', $partList);
        $this->assign("auto",$auto);
        $this->display();
    }

    public function share2(){
        $O=M("order");
        $map['order_id']=$_GET['id'];
        $order=$O->field("model_id,total_price,all_price,js_id")->where($map)->find();
        $auto=M("auto_model")->where("model_id=".$order['model_id'])->find();
        $partList = M('order_info')->where($map)->select();
        $log=M("order_log")->field("action_id,name,val,bad_level,type,time,image")->where($map)->order("log_id desc")->select();

        $data =  array();
        $Unit = C('UNIT');
        foreach ($log as $li){
            switch ($li['name']){
                case "制冷效果检测":
                    $li['biaozhun']='测量值小于12°C为正常';
                    if($li['val']<=12){
                        $li['compare'] = '正常';
                    }else{
                        $li['compare'] = '异常';
                    }
                    break;
                default:;
            }
            if($li['type'] == 'sg'){
                if($Unit[$li['action_id']]){
                    $li['val'] = $li['val'].' '.$Unit[$li['action_id']];
                }
            }
            $data[] = $li;
        }

        $signature=M("jishi")->where("js_id=".$order['js_id'])->getField("signature");
        $this->assign('signature', $signature);


        $this->assign('log', $data);
        $this->assign('lastLog', $log[0]);
        $this->assign('order', $order);
        $this->assign('partList', $partList);
        $this->assign("auto",$auto);
        $this->display();
    }

    //分享立减10元
    public function privilegeShare(){
        $Model=new Model();
        $order_id=time().rand(100, 999);
        $query="update hx_order set order_num='".$order_id."' ,privilege='分享朋友圈立减10元',all_price=all_price-10 where order_id=".$_REQUEST['id']." and privilege='';";
        $order=$Model->query($query);
        if($order!==false){
            $this->ajaxReturn($order,$order_id,1);
        }else{
            $this->ajaxReturn($order,"网络忙，请稍后再试！",0);
        }
    }

    //分享立减10元
    public function privilegeShareSummer(){
        $Model=new Model();
        $order_id=time().rand(100, 999);
        $query="update hx_order set order_num='".$order_id."' ,privilege='分享朋友圈立减224元',all_price=all_price-224 where order_id=".$_REQUEST['id']." and privilege='';";
        $order=$Model->query($query);
        if($order!==false){
            $this->ajaxReturn($order,$order_id,1);
        }else{
            $this->ajaxReturn($order,"网络忙，请稍后再试！",0);
        }
    }


    /*
    *验证短信码*
    */
    public function valCode(){
        $S = M("sms");
        $mapSms['desc'] = $_POST['code'];
        $mapSms['to_phone'] = $_POST['phone'];
        $mapSms['isused'] = 0;

        $code = $S->field("create_time")->where($mapSms)->order("create_time desc")->limit(1)->select();

        if ($code == false) {
            $this->ajaxReturn(null, "验证码错误", -6);
        }
        $code = $code[0]['create_time'];
        $S->where($mapSms)->setField("isused",1);
        if (($code + 5 * 60) < time()) {
            $this->ajaxReturn(null, "验证码已过期，请重新获取", -8);
        }else{
            $this->login();
            $this->ajaxReturn(null, "验证码正确", 1);
        }

    }


    //维修厂时间轴订单列表
    private function stepList($order_id) {
        $map['order_id']=$order_id;

        $log = M('orderlog')->where($map)->select();

        $logList[1]['title'] = "支付时间";
        $logList[1]['action'] = "PAY";

        $logList[2]['title'] = "收货时间";
        $logList[2]['action'] = 'SH';

        foreach ($log as $l){
            if($l['action'] == 'PAY'){
                $logList[1]['time'] = $l['time'];
            }else if($l['action'] == 'SH'){
                $logList[2]['time'] = $l['time'];
            }
        }
        return $logList;
    }

    public function login(){
        if(!empty($_POST)){

            $U=M("user");
            if(!empty($_SESSION['open_id'])){
                $U->where("username=".$_POST['phone'])->setField("open_id",$_SESSION['open_id']);
            }
            $map['username']=$_POST['phone'];
            $field="user_id,username,nickname,head_image,realname,address";
            $Info=$U->field($field)->where($map)->find();

            if($Info){                                  //初始化验证用户
                $U = M('user_auto');
                $model = $U->join('hx_auto_model m on hx_user_auto.model_id=m.model_id')->where("user_id=".$Info['user_id']." and hx_user_auto.default=1")->find();
                
                $Info['model'] = $model;
                $_SESSION['order']['model_id'] = $model['model_id'];
                $_SESSION['order']['realname']=$Info["realname"];
                $_SESSION['order']['phone']=$Info["username"];
                $_SESSION['user'] = $Info;              //session记录数据
                $_SESSION['location']=$Info['city'];
            }
        }else{
            $this->display();
        }
    }

    //验证优惠码
    public function valCoupon(){
        $map['code'] = $_REQUEST['code'];
        $data = M('coupon_user as l')->join("left join hx_coupon as c ON c.c_id=l.c_id")->field('c.c_id,l.number,l.code,l.status,c.money,c.content,c.low_money,c.high_money,c.type')->where($map)->find();

        if($data){
            if($data['status']==1){
                $this->ajaxReturn($data,'此优惠券可使用',1);
            }elseif($data['status']==0){
                $this->ajaxReturn($data,'此优惠券已使用',-1003);
            }else{
                $this->ajaxReturn($data,'此优惠券已过期',-1004);
            }
        }else{
            $this->ajaxReturn(null,'优惠码错误',-1002);
        }
    }


    //使用优惠券
    public function userCoupon(){
        $map['code'] = $_REQUEST['code'];

        $where="code=".$_REQUEST['code']." and ( open_id = '".$_SESSION['open_id']."' or user_id='".$_SESSION['user']['user_id']."')";

        $data = M('coupon_user as l')->join("left join hx_coupon as c ON c.c_id=l.c_id")->field('c.c_id,l.cu_id,l.number,l.code,l.status,c.money,c.content,c.low_money,c.high_money,c.type')->where($where)->find();

        if($data){
            if($data['status']==1){
                //更新优惠券状态为已用
                $coupon=M('coupon_user');
                $dataCoupon['status']=0;
                $dataCoupon['cu_id']=$data['cu_id'];
                $dataCoupon['rand_money']=$data['money'];
                $coupon->save($dataCoupon);

                $Model=new Model();
                $order_id=time().rand(100, 999);
                $query="update hx_order set order_num='".$order_id."' ,all_price=all_price-".$data['money']." ,cu_id='".$data['cu_id']."' where order_id=".$_POST['orderId']." ;";
                $order=$Model->query($query);

                if($order!==false){
                    $this->ajaxReturn($data,'成功使用优惠券',1);
                }else{
                    $this->ajaxReturn($data,"网络忙，请稍后再试！",0);
                }

                
            }elseif($data['status']==0){
                $this->ajaxReturn($data,'此优惠券已使用',-1003);
            }else{
                $this->ajaxReturn($data,'此优惠券已过期',-1004);
            }
        }else{
            $this->ajaxReturn(null,'优惠码错误',-1002);
        }
    }

   
    //获取免单券
    public function getCoupon(){
        if(empty($_REQUEST['user_id'])){
            $this->ajaxReturn(null,'缺少参数',-1001);
        }
        
        $m =new Model();
        $sqls ="UPDATE hx_coupon set sum=sum+1,get_count=get_count+1 WHERE c_id=4";
        $m->query($sqls);
        
        $CUser = M('coupon_user')->field('id')->where('c_id=4 and user_id='.$_REQUEST['user_id'])->find();
        $CUser ? $this->ajaxReturn(null,'您已经拥有免单券了哦',-1004) : 1 ;
        
        $time = time();                                                             //服务器时间戳
        $date = date("Y-m-d");                                                      //当前服务器日期
        $am1 = strtotime($date." 00:00:00");                                            //上午时间戳
        $am2 = strtotime($date." 23:59:59");
        $pm1 = strtotime($date." 00:00:00");                                            //下午时间戳
        $pm2 = strtotime($date." 23:59:59");
        $Last = 0;                                                                  //剩余名额
        if($time>=$am && $time<=$pm){                                               //11~16
            $Data = M('coupon_user')->field('count(id) as count')->where("get_time>='$am1' and get_time<='$am2' and c_id=4")->find();
        }elseif($time>=$pm){                                                        //16~24
            $Data = M('coupon_user')->field('count(id) as count')->where("get_time>='$pm1' and get_time<='$pm2' and c_id=4")->find();
        }else{
            $this->ajaxReturn(null,'活动时间还未开始哦',-1001);
        }
        if($Data['count'] <50){
            $num = rand(1,100);
            if($num>=60){
                $Coupon = M('coupon_user');
                $Info['code'] = rand(10000,99999).rand(10000,99999).rand(100000,999999);
                $Info['number'] = rand(1000,9999).rand(1000,9999);
                $Money = rand(256,1000);    //免单金额
                //$Info['type'] = 2;
                $Info['c_id'] = 4;
                $Info['get_time'] = time();
                $Info['user_id'] = $_REQUEST['user_id'];
                $Info['status'] = 2;    //未激活
                $Coupon->startTrans();
                $res = $Coupon->add($Info);
                if($time>=$am && $time<=$pm){                                               //11~16
                    $Data = M('coupon_user')->field('count(id) as count')->where("get_time>='$am1' and get_time<='$am2' and c_id=4")->find();
                }elseif($time>=$pm){                                                        //16~24
                    $Data = M('coupon_user')->field('count(id) as count')->where("get_time>='$pm1' and get_time<='$pm2' and c_id=4")->find();
                }
                if($res && $Data['count'] <=50){
                    $Info['money'] = $Money;
                    $Coupon->commit();
                    $Info['count'] = 50 - $Data['count'];
                    $this->ajaxReturn($Info,'免单券一张，价值1000元',1);
                }else{
                    $Coupon->rollback();
                    $this->ajaxReturn(50-$Data['count'],'手慢哦,已经抢光啦',-1002);
                }
            }else{
                $this->ajaxReturn(50-$Data['count'],'没抢到,再接再厉',-1003);
            }
        }else{
            $this->ajaxReturn(50-$Data['count'],'手慢哦,已经抢光啦',-1002);
        }
    }
    
    //微信验证用户
    public function verifyUser(){
        if(empty($_REQUEST['phone'])){
            $this->ajaxReturn(null,'缺少参数',-1001);
        }
        $phone = $_REQUEST['phone'];
        
            $Info = M('user')->field('user_id,open_id,username,nickname,realname,address')->where("username=$phone")->find();
            if($Info){
                $data['user_id'] = $Info['user_id'];
                if($_SESSION['open_id']){
                    $data['open_id'] = $_SESSION['open_id'];
                }
                $res = M('user')->save($data);

                $model = M('user_auto')->field("model_id,model_name,model_pl,model_year,model_logo")->where("user_id=".$Info['user_id']." and hx_user_auto.default=1")->find();
                $Info['model'] = $model;
                $_SESSION['order']['model_id'] = $model['model_id'];
                $_SESSION['user'] = $Info;
                $_SESSION['order']['realname']=$Info["realname"];
                $_SESSION['order']['phone']=$Info["username"];
                $this->ajaxReturn($Info,'绑定成功',1);
            }else{
                //注册用户并插入数据
                $data['create_time'] = time();
                $data['tel'] = $phone;
                if($_SESSION['open_id']){
                    $data['open_id'] = $_SESSION['open_id'];
                }
                $data['username'] = $phone;
                $data['nickname'] = '';
                $data['password'] = md5("123456");
                $user_id = M('user')->add($data);
                if($user_id){
                    $data['user_id'] = $user_id;
                    $_SESSION['user'] = $data;
                    $_SESSION['order']['phone']=$phone;
                    $this->ajaxReturn($Info,'注册成功',1);
                }else{
                    $this->ajaxReturn(null,'注册失败',-1003);
                }
            }

    }
    
    //聊天系统注册
    public function chatReg($Id) {
        $data = array();
        $data['userName'] = $_POST['username'].$Id;
        $data['userPassword'] = $_POST['pwd'];
        $data['userNickname'] = $_POST['username'];
        $data['userDescription'] = $_POST['username'];
        $o="";
        foreach ($data as $k=>$v){
            $o.= "$k=".urlencode($v)."&";
        }
        $data=substr($o,0,-1);
        $url = 'http://chat.haixiuyizhan.com:8080/skapi/v2/user/register';
        $res = $this->https_request($url,$data);
        if($res){
            $res = json_decode($res);
            if($res->resultCode==1){
                return $res->gid;
            }
        }
    }

    //视频直播

 
    public function live(){

        //if(!empty($_GET['phone'])&&empty($_SESSION['user'])){
        if(!empty($_GET['phone'])){
            $_POST['phone']=$_GET['phone'];
            $this->login();
        }

        if(empty($_GET['orderId'])){
            $map['user_id'] = $_SESSION['user']['user_id'];
            $map['status']=array("BETWEEN","6,67");
            $map['pay_type']=array("eq",0);
            //$map['type']=array("in","1,2,999");
        }else{
            $map['order_id']=$_GET['orderId'];
        }

        $Model = M('order');
        $order = $Model->where($map)->order("order_id desc")->find();
        if($order['address_start']!=""&&$_GET['from']!="adj"){
            redirect(U('/adj/'));
        }
        $data = array();
        $data['is_server'] = 0;
        if($order&&($order['status']==50||$order['status']==60)){
            $data['is_server'] = $order['order_id'];

            $video = C("VIDEO");
            if($order['gw_id']==1){
                $order['video1'] = $video['1-1'];
                $order['video2'] = $video['1-2'];
            }elseif($order['gw_id']==2){
                $order['video1'] = $video['2-1'];
                $order['video2'] = $video['2-2'];
            }
            $data['order'] = $order;

            $this->assign("order",$data);
            $this->display("live");
        }else{
            $this->display("unLive");
        }
        
    }

    public function getOrderPeijian(){
        $map['order_id']=$_POST['order_id'];
        $model_id=M("order")->where($map)->getField("model_id");
        $capacity=M("auto_model")->where("model_id=".$model_id)->getField("capacity");
        $PJ=M("peijian");
        $jiyou=$PJ->where("pj_id=".$_POST['jyId'])->find();
        if($jiyou){
            $this->ajaxReturn($jiyou,$capacity,1); 
        }else{
            $this->ajaxReturn(false,"",0);
        }
    }


    //全监控查看
    public function liveTest(){
        $this->display();
    }

    //获取订单总价
    public function getOrderPrice(){
        $map['order_id']=$_POST['order_id'];
        $O=M("order");
        $price=$O->field("all_price,total_price")->where($map)->find();
        if($price){
            $this->ajaxReturn($price,"",1); 
        }else{
            $this->ajaxReturn(false,"",0);
        }
    }

    //保存签名图片
    public function signature(){
        $_POST['img']=str_replace('data:image/png;base64,', '', $_POST['img']);

        $img = base64_decode($_POST['img']);
        $path ="Uploads/" . date("Ymd") . "/";
        if (!is_dir($path)){
            mkdir($path);
        }
        $name=$path.time().rand(100, 999).".png";
        $fileSize = file_put_contents($name, $img);
        if($fileSize){
            $data['log_id']=$_POST['logId'];
            $data['image']=$name;
            $data['val']=1;
            $data['status']=1;
            $res=M("order_log")->save($data);
            if($res){
                $this->ajaxReturn($name,"签名成功",1);
            }
            $this->ajaxReturn($name,"签名保存失败，请重试！",0);
        }else{
            $this->ajaxReturn($name,"签名保存失败，请重试！",0);
        }
    }

    /**
     *  获取维修厂方法--------------只查询了主表hx_company
     *   $latitude    纬度y
     *   $longitude   经度   x
     *  $map   条件
     *  $distace_offset  距离范围
     *  $order              排序
     *                //纬度↓     经度 ↓   where条件↓  页↓   条↓    多少距离以内↓         排序↓              字段↓
     */
    function distance_company($latitude,$longitude,$map = '1',$p='',$n='',$distace_offset = false , $order = 'juli asc',$field=''){
        $C = M('company');
        $where ='hx_company.status=1 and  ';
        if($distace_offset){
            $distace_offset = $distace_offset/100;
        }
        $offset =  "hx_company.p_y > $latitude-$distace_offset and hx_company.p_y < $latitude+$distace_offset and hx_company.p_x > $longitude-$distace_offset and hx_company.p_x < $longitude+$distace_offset and ";
        $distace_offset ? $where =$offset.$where :'';
        $map = $where.$map;
        //分页
        $page = empty($p) ? 1 : ($p-1)*$n;
        $num = empty($n) ? 5 : ($n);
        $field1 = "ACOS(SIN(('$latitude' * 3.1415) / 180 ) *SIN((hx_company.p_y * 3.1415) / 180 ) +COS(('$latitude' * 3.1415) / 180 ) * COS((hx_company.p_y * 3.1415) / 180 ) *COS(('$longitude'* 3.1415) / 180 - (hx_company.p_x * 3.1415) / 180 ) ) * 6380 as juli,";
        $field2=$field1."hx_company.id,hx_company.username,hx_company.headImage,hx_company.name,hx_company.p_x,hx_company.p_y,hx_company.address,hx_company.tel,hx_company.head,hx_company.average,hx_company.status,hx_company.danshu";
        $field3=$field2;//"xiche,baoyang,meirong,weixiu,bjyq,jiuyuan,yisuijian,shengji,mianfei_xc,mianfei_jiance,tuoche,chedaojia,daibuche";
        
        $comp = $C->field($field3)->where($map)->limit($page,$num)->order($order)->select();
            //echo $C->getLastSql();
        foreach($comp as $key=>$value){
                
            //将空替换 ''
            foreach($value as $ke=>$va){
                if($va == '' ||$va == 'null'){
                    $comp[$key][$ke]='';
                }
            }
    
            $comp[$key]['headImage']  = $value['headImage'];
            $comp[$key]['juli'] = round($value['juli'],1).'km';
        }
        if($comp){
            return  $comp;
        }else{
            return '';
        }
    }

    /**
     * @根据地理位置查询最近维修厂
     * 
     */
    function getAddressNearCompany(){
        
        if(empty($_REQUEST['address'])){
            $this->ajaxReturn('','缺少参数',-1001); 
        }
        $address = $_REQUEST['address'];
        $url ="http://api.map.baidu.com/geocoder/v2/?address=".$address."&output=json&ak=18713dd89f5ebc7c730768c641fb3039&callback=";
        $data_address = json_decode(file_get_contents($url),true);
        $array_xy = $data_address['result']['location'];
        
        if($array_xy){
            $data   =   $this->distance_company($array_xy['lat'], $array_xy['lng'],1,1,20);
            if($data){
    
                $this->ajaxReturn($data,'成功',1);
            
            }else{
                
                $this->ajaxReturn('','失败',0);
            }
        }else{
            $this->ajaxReturn('','失败',0);
            
        }
    }

    public function pay($order_id,$type=null){
        vendor('WxPay/WxPayPubHelper');
        //使用jsapi接口
        $jsApi = new JsApi_pub();
    
        $openid = $_SESSION['open_id'];
        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $unifiedOrder = new UnifiedOrder_pub();
    
        $Info = M('order')->where("order_id=$order_id")->find();
        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid","$openid");//商品描述
        $unifiedOrder->setParameter("body",$Info['order_name']);//商品描述
        //自定义订单号，此处仅作举例
        $timeStamp = time();
        $out_trade_no = WxPayConf_pub::APPID."$timeStamp";
        $order_num = $Info['order_num'];
        $money = $Info['all_price']*100;
        if($Info['user_id']==208){
            $money = 1;
        }
        $unifiedOrder->setParameter("out_trade_no","$order_num");//商户订单号
        $unifiedOrder->setParameter("total_fee","$money");//总金额
        $unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
        //var_dump($unifiedOrder);exit;
        $prepay_id = $unifiedOrder->getPrepayId();
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);
         
        $jsApiParameters = $jsApi->getParameters();
        if($type){
            echo $jsApiParameters;
        }else{
            return $jsApiParameters;
        }
    }

    //支付宝手机支付
    public function alipaywap()
    {
        require_once("./payment/alipay/wap/alipay.config.php");
        require_once("./payment/alipay/wap/lib/alipay_submit.class.php");
        /**************************调用授权接口alipay.wap.trade.create.direct获取授权码token**************************/
        //dump($alipay_config);exit;
        //返回格式
        $format = "xml";//必填，不需要修改
        //返回格式
        $v = "2.0";//必填，不需要修改
        //请求号
        $req_id = date('Ymdhis');//必填，须保证每次请求都是唯一
        //**req_data详细信息**
        //服务器异步通知页面路径
        $notify_url = "http://m.99qby.com/pay/alipay_notify_wap";
        //需http://格式的完整路径，不允许加?id=123这类自定义参数
    
        //页面跳转同步通知页面路径
        //$call_back_url = "http://m.99qby.com/alipay/wap/call_back_url.php";
        $call_back_url = "http://m.99qby.com/mobile/step3";
        if($_REQUEST['info']){
            $call_back_url = "http://m.99qby.com/mobile/comment/order_id/".$_REQUEST['order_id'];
        }
        //需http://格式的完整路径，不允许加?id=123这类自定义参数
    
        //操作中断返回地址
        $merchant_url = "http://m.99qby.com/mobile/step2";
        //用户付款中途退出返回商户的地址。需http://格式的完整路径，不允许加?id=123这类自定义参数
        $order_id = $_REQUEST['order_id'];
        $Info = M('order')->where("order_id=$order_id")->find();

        //商户订单号
        $out_trade_no = $Info['order_num'];//$_POST['WIDout_trade_no'];
        //商户网站订单系统中唯一订单号，必填
    
        //订单名称
        $subject = $Info['order_name'];//$_POST['WIDsubject'];//必填
    
        //付款金额
        $total_fee = $Info['all_price'];//$_POST['WIDtotal_fee'];//必填
        if($Info['user_id'] == 208){
            $total_fee = 0.01;
        }
    
        //请求业务参数详细
        $req_data = '<direct_trade_create_req><notify_url>' . $notify_url . '</notify_url><call_back_url>' . $call_back_url . '</call_back_url><seller_account_name>' . trim($alipay_config['seller_email']) . '</seller_account_name><out_trade_no>' . $out_trade_no . '</out_trade_no><subject>' . $subject . '</subject><total_fee>' . $total_fee . '</total_fee><merchant_url>' . $merchant_url . '</merchant_url></direct_trade_create_req>';
    
        /************************************************************/
    
        //构造要请求的参数数组，无需改动
        $para_token = array(
                "service" => "alipay.wap.trade.create.direct",
                "partner" => trim($alipay_config['partner']),
                "sec_id" => trim($alipay_config['sign_type']),
                "format"    => $format,
                "v" => $v,
                "req_id"    => $req_id,
                "req_data"  => $req_data,
                "_input_charset"    => trim(strtolower($alipay_config['input_charset']))
        );
    
        //建立请求
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestHttp($para_token);
    
        //URLDECODE返回的信息
        $html_text = urldecode($html_text);
    
        //解析远程模拟提交后返回的信息
        $para_html_text = $alipaySubmit->parseResponse($html_text);
    
        //获取request_token
        $request_token = $para_html_text['request_token'];
    
    
        /**************************根据授权码token调用交易接口alipay.wap.auth.authAndExecute**************************/
    
        //业务详细
        $req_data = '<auth_and_execute_req><request_token>' . $request_token . '</request_token></auth_and_execute_req>';
        //必填
    
        //构造要请求的参数数组，无需改动
        $parameter = array(
                "service" => "alipay.wap.auth.authAndExecute",
                "partner" => trim($alipay_config['partner']),
                "sec_id" => trim($alipay_config['sign_type']),
                "format"    => $format,
                "v" => $v,
                "req_id"    => $req_id,
                "req_data"  => $req_data,
                "_input_charset"    => trim(strtolower($alipay_config['input_charset']))
        );
    
        //建立请求
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter, 'get', ' ');
        echo $html_text;
    }

    public function comment(){
        $this->display();
    }
    
    public function toWX(){
        $this->display();
    }
    
}

?>